package com.honey.eclipse.formatter.style;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public  class BaseStyleFormatterSetting implements StyleFormatterSettings{

	private String settingFile = null;
	
	public BaseStyleFormatterSetting(String settingFile){
		this.settingFile = settingFile;
	}
	
	@Override
	public Map<String, String> getSettings() {
		Map<String, String> answer = null;
		try {
			InputStream in = new FileInputStream( settingFile);
			answer = parserSettingFile(in);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return answer;
	}
	
	private static Map<String, String> parserSettingFile(InputStream settings) throws Exception {
		SAXHandler handler = new SAXHandler();
		SAXParserFactory saxparserfactory = SAXParserFactory.newInstance();
		SAXParser saxparser = saxparserfactory.newSAXParser();
		saxparser.parse(settings, handler);
		return handler.getSetting();
	}

	static class SAXHandler extends DefaultHandler {

		private Map<String, String> setting = null;

		public SAXHandler() {
			setting = new HashMap<String, String>();
		}

		@Override
		public void startElement(String uri, String localName, String name,
				Attributes attributes) throws SAXException {
			if ("setting".equalsIgnoreCase(name)) {
				String key = attributes.getValue("id");
				String value = attributes.getValue("value");
				if (key != null && key.length() > 0 && value != null
						&& value.length() > 0) {
					setting.put(key, value);
				}
			}
		}

		public Map<String, String> getSetting() {
			return setting;
		}
	}
	
}
